package com.chagee.store.operation.server.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.HttpResponse;
import com.chagee.base.utils.HttpResponseUtil;
import com.chagee.store.operation.api.enums.OrderAppealTypeEnum;
import com.chagee.store.operation.api.request.WorkOrderRequest;
import com.chagee.store.operation.common.annotation.FiledDesc;
import com.chagee.store.operation.common.constant.FeiShuMessageConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.config.EvaluateDictConfig;
import com.chagee.store.operation.server.config.LarkMessageConfig;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.model.bo.*;
import com.chagee.store.operation.server.model.info.EvaluateDictInfo;
import com.chagee.store.operation.server.model.info.MessageInfo;
import com.chagee.store.operation.server.service.biz.FeiShuMessageBizService;
import com.chagee.store.operation.server.service.biz.PaymentBizService;
import com.chagee.store.operation.server.utils.DateUtil;
import com.lark.oapi.Client;
import com.lark.oapi.service.contact.v3.model.*;
import com.lark.oapi.service.im.v1.model.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author : hk
 * @Date : 2024/12/11
 */

@Slf4j
@RestController
@RequestMapping("/test")
public class WorkOrderTestController {
	private static final String TO_PROCESS = "去处理";

	private static final String appid = "cli_a6e525143811900c";
	private static final String AppSecret = "PZrmdo7ozQbjjFGtlkgMJettOKmx72it";

	private FeiShuMessageBizService feiShuMessageBizService;

	@Resource
	private LarkMessageConfig larkMessageConfig;

	@Resource
	private EvaluateDictConfig evaluateDictConfig;

	@Resource
	private PaymentBizService paymentBizService;
	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Value("${pushEndDate.endDate: 01:00:00}")
	private String pushEndDate;

	@GetMapping("/test1")
	@ApiOperation("PC端开早打样工单获取数据字典")
	public Boolean dict() {


		String endDate = DateUtil.format(new Date(), DateUtil.DEFAULT_DATE_PATTERN) + pushEndDate;
		System.out.println(endDate);
		Client client = Client.newBuilder(appid, AppSecret).build();
		String openId = getFeiShuOpenId(client, "13074063958");
		log.info("openId {}", openId);
		//构建消息内容参数

		return sendMessage(client, openId, "夜洁工单未接单门店清单");
	}

	public boolean sendMessage(Client client, String receiveId, String title) {
		//String content = getMessageContent(title, "上海子公司的下列门店昨日三方夜洁工单未接单，请及时跟进关注", TO_PROCESS, "");
		//log.info("send feiShu message:{}", JSON.toJSONString(content));
		FeiShuMsgContentBO msgContent = new FeiShuMsgContentBO();

		msgContent.setConfig(new FeiShuConfigBO().setWide_screen_mode(true));
		msgContent.setHeader(new FeiShuHeaderBO().setTitle(new FeiShuTitleBO().setContent("夜洁工单未接单门店清单")));

		List<Object> elementsList = new ArrayList<>();
		//推送文案
		FeiShuCopywritingBO feiShuCopywritingBO = new FeiShuCopywritingBO().setText(new FeiShuCopywritingBO.CopywritingInfo().setContent("上海子公司的下列门店昨日三方夜洁工单未接单，请及时跟进关注"));
		elementsList.add(feiShuCopywritingBO);

		ArrayList<OrderTakingExcelBO> orderTakingExcelBOS1 = new ArrayList<>();
		OrderTakingExcelBO excelBO = new OrderTakingExcelBO("测试", "测试", "测试");
		OrderTakingExcelBO excelBO1 = new OrderTakingExcelBO("测试", "测试", "测试");
		orderTakingExcelBOS1.add(excelBO);
		orderTakingExcelBOS1.add(excelBO1);
		List<Object> orderTakingExcelBOS = Arrays.asList(orderTakingExcelBOS1.toArray());

		List<Object> changeInfo = getChangeInfo(OrderTakingExcelBO.class);
		System.out.println(JSON.toJSONString(changeInfo));

		FeiShuTableBO feiShuTableBO = new FeiShuTableBO().setColumns(changeInfo).setRows(orderTakingExcelBOS);
		elementsList.add(feiShuTableBO);

		msgContent.setElements(elementsList);
		String content = JSON.toJSONString(msgContent);

		//String content = "{\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"上海子公司的下列门店昨日三方夜洁工单未接单，请及时跟进关注\"}},{\"freeze_first_column\":true,\"columns\":[{\"name\":\"storeNo\",\"display_name\":\"门店编号\",\"data_type\":\"text\",\"horizontal_align\":\"left\",\"vertical_align\":\"top\",\"width\":\"auto\"},{\"name\":\"storeName\",\"display_name\":\"门店名称\",\"data_type\":\"text\",\"horizontal_align\":\"left\",\"vertical_align\":\"top\",\"width\":\"auto\"},{\"name\":\"companyName\",\"display_name\":\"所属子公司\",\"data_type\":\"text\",\"horizontal_align\":\"left\",\"vertical_align\":\"top\",\"width\":\"auto\"}],\"header_style\":{\"text_size\":\"normal\",\"background_style\":\"none\",\"bold\":true,\"text_color\":\"grey\",\"lines\":1,\"text_align\":\"left\"},\"row_height\":\"low\",\"tag\":\"table\",\"rows\":[{\"storeNo\":\"123\",\"companyName\":\"3424\",\"storeName\":\"321312\"}],\"headerStyle\":{\"text_size\":\"normal\",\"background_style\":\"none\",\"bold\":true,\"text_color\":\"grey\",\"lines\":1,\"text_align\":\"left\"},\"page_size\":10}],\"header\":{\"template\":\"turquoise\",\"title\":{\"tag\":\"plain_text\",\"content\":\"夜洁工单未接单门店清单\"}},\"config\":{\"wide_screen_mode\":true}}";
		// 创建请求对象
		log.info("content:{}", JSON.toJSONString(content));
		CreateMessageReq req = CreateMessageReq.newBuilder()
			.receiveIdType(FeiShuMessageConstant.RECEIVE_ID_TYPE)
			.createMessageReqBody(CreateMessageReqBody.newBuilder()
				.receiveId(receiveId)
				.msgType("interactive")
				.content(content)
				.build())
			.build();

		// 发起请求
		CreateMessageResp resp = null;
		try {
			resp = client.im().message().create(req);
		} catch (Exception e) {
			log.error("send feiShu message: fail.",  e);
			throw new BizException(BizErrorCode.SEND_LARK_MESSAGE_FAIL);
		}
		log.info("send feiShu message:{} response data:{}, code:{}, msg:", JSON.toJSONString(resp.getData()), resp.getCode(), resp.getMsg());
		// 业务失败
		if (resp.success()) {
			return true;
		}
		throw new BizException(resp.getMsg());
	}
	public static <T> List<Object> getChangeInfo(Class data) {
		List<Object> columnsList = new ArrayList<>();

		Field[] fields = data.getDeclaredFields();
		for (Field field : fields) {

			FiledDesc annotation = field.getAnnotation(FiledDesc.class);
			if (Objects.isNull(annotation)) {
				continue;
			}
			field.setAccessible(true);
			//字段值
			String name = field.getName();
			//注解
			String value = annotation.value();

			String ttt = "{\n" +
				"\t\"name\": \"${code}\",\n" +
				"\t\"display_name\": \"${columnName}\",\n" +
				"\t\"data_type\": \"text\",\n" +
				"\t\"horizontal_align\": \"left\",\n" +
				"\t\"vertical_align\": \"top\",\n" +
				"\t\"width\": \"auto\"\n" +
				"}";
			FeiShuColumnsBO feiShuColumnsBO = new FeiShuColumnsBO().setName(name).setDisplay_name(value);
			//Object s = JSON.parseObject(ttt).replace("${" + "code" + "}", name).replace("${" + "columnName" + "}", value);

			columnsList.add(feiShuColumnsBO);
		}
		return columnsList;
	}

	private String getMessageContent(String title, String content, String buttonMsg, String url) {
		String aa = "C7FD8ABC-E9B7-4498-8CD0-38ABC5F24733";

		String purl = "https://chagee20.oss-cn-shanghai.aliyuncs.com/chagee20/images/20241125/1732533170833/打烊结算模板.xlsx";
		StringBuilder builder = new StringBuilder();
		builder.append("{"+
			"\"config\": {"+
			"\"wide_screen_mode\": true" +
			"}," +
			"\"elements\": [{"+
			"\"tag\": \"div\","+
			"\"text\": {" +
			"\"content\": \""+ content +"\"," +
			"\"tag\": \"lark_md\""+
			"}" +
			"}");
		if (StringUtils.isNotBlank(url)) {
			builder.append(", {" +
				"\"actions\": [{" +
				"\"tag\": \"button\"," +
				"\"text\": {" +
				"\"content\": \"" + buttonMsg + "\"," +
				"\"tag\": \"plain_text\"" +
				"}," +
				"\"type\": \"primary\"," +
				"\"url\": \"" + url + "\"" +
				"}]," +
				"\"tag\": \"action\"" +
				"}");
		}
//		builder.append(",{\n" +
//			"\t\"tag\": \"markdown\",\n" +
//			"\t\"content\": \"[夜洁工单未接单门店清单](" + purl + ")\\n\"\n" +
//			"}");
		builder.append(",{\"tag\":\"markdown\",\"content\":\"|Syntax      | Description |\\n|-------- | -------- |\\n|Header      | Title       |\\n|Paragraph   | Text        |\"}");
		builder.append("]," +
			"\"header\": {"+
			"\"template\": \"turquoise\"," +
			"\"title\": {" +
			"\"content\": \""+ title +"\"," +
			"\"tag\": \"plain_text\"}}}");
		return builder.toString();
	}
	private String getFeiShuOpenId(Client client, String phone) {
		// 创建请求对象
		BatchGetIdUserReq req = BatchGetIdUserReq.newBuilder()
			.userIdType(FeiShuMessageConstant.RECEIVE_ID_TYPE)
			.batchGetIdUserReqBody(BatchGetIdUserReqBody.newBuilder()
				.mobiles(new String[] {
					phone
				})
				.build())
			.build();

		// 发起请求
		BatchGetIdUserResp resp = null;
		try {
			resp = client.contact().user().batchGetId(req);
		} catch (Exception e) {
			log.error("query openId from feiShu fail. phone:{}", phone,  e);
			throw new BizException(BizErrorCode.GET_LARK_OPENID_FAIL);
		}

		log.info("query openId from feiShu response data:{}, phone:{}, code:{}, msg:{}", JSON.toJSONString(resp.getData()), phone, resp.getCode(), resp.getMsg());
		// 处理服务端错误
		if(!resp.success()) {
			throw new BizException(resp.getMsg());
		}

		UserContactInfo[] userList = resp.getData().getUserList();
		UserContactInfo userContactInfo = userList[0];
		if (Objects.nonNull(userContactInfo) && StringUtils.isNotBlank(userContactInfo.getUserId())) {
			return userContactInfo.getUserId();
		}

		throw new BizException("openId is empty");
	}



	@PostMapping("/queryOrder")
	public HttpResponse<Page<WorkOrderDO>> queryOrder(@RequestBody WorkOrderRequest request) {

		Page<WorkOrderDO> page = new Page<>(1, 10);
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		if (StringUtils.isNotBlank(request.getAppealFlag())) {
			if (OrderAppealTypeEnum.APPEAL.name().equals(request.getAppealFlag())) {
				wrapper.isNotNull(WorkOrderDO::getAppealResult);
			}
			if (OrderAppealTypeEnum.NO_APPEAL.name().equals(request.getAppealFlag())) {
				wrapper.isNull(WorkOrderDO::getAppealResult);
			}
		}
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page,wrapper);

		return HttpResponseUtil.success(workOrderDOS);
	}



	@GetMapping("/confirmPayment")
	@ApiOperation("结算单线下支付")
	public List<String> confirmPayment() {
		List<MessageInfo> infos = larkMessageConfig.getInfos();
		List<String> collect = infos.stream().filter(s -> s.getType().equals("appealNotice")).map(MessageInfo::getMessage).collect(Collectors.toList());
		EvaluateDictInfo a01 = evaluateDictConfig.getByType("A01");
		collect.add(a01.getEvaluateType());
		return collect;
	}

	@GetMapping("/createOrder/{orderNo}")
	@ApiOperation("结算单线下支付")
	public String createOrder(@PathVariable("orderNo") String orderNo) {
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(orderNo);
		String order = paymentBizService.createOrder(storeSettlementDO,"1234");
		return order;
	}

}
